<template>
  <PageContainer>
    <Header title="订单详情" :is-box-shadow="false" />
    <Loading v-model="loading">
      <TopStatusView
        v-if="orderInfo && orderInfo.refundStatus !== OrderRefundStatusEnum.PARTREFUNDED"
        :order-state="orderInfo.orderState"
        :pay-state="orderInfo.payState"
        :expire-second="orderInfo.expireSecond"
        :remark="orderInfo.remark"
        @refresh="handleRefresh"
      />
      <view style="background-color: #fff">
        <TopActivityInfo
          :cover-url="activityInfo?.coverUrl"
          :address="activityInfo?.address"
          :address-name="activityInfo?.addressName"
          :start-time="activityInfo?.startTime"
          :title="activityInfo?.title"
          :latitude="activityInfo?.latitude"
          :longitude="activityInfo?.longitude"
          :activity-status="activityInfo?.activityStatus"
          @click="toActivityDetail"
        />
      </view>
      <view class="pa-12">
        <CellBox title="报名信息" :list="applicantInfo" />
        <RegistrationInfo
          v-if="!loading"
          :register-info-list="registerInfoList"
          :ticket-name="suborderInfo?.activityTicketName"
          :activity-status="activityInfo?.activityStatus"
          :activity-title="activityInfo?.title"
          @refresh="__init()"
        />
        <CellBox title="其他信息" :list="ticketPurchaseInfo" />
      </view>
      <TButtonGroup
        v-if="
          orderInfo &&
          orderInfo?.payState !== OrderPayStateEnum.HAVEPAID &&
          orderInfo?.orderState !== OrderStateEnum.CLOSED
        "
        :styles="{
          backgroundColor: '#fff',
          justifyContent: 'flex-end',
          boxShadow: '0px -4rpx 24rpx 0px rgba(150, 151, 153, 0.16)',
        }"
      >
        <TButton
          text="取消订单"
          type="none"
          :customStyle="{
            display: 'inline-block',
            backgroundColor: 'transparent',
            color: '#292928',
            border: '1px solid #CCCCC8',
          }"
          custom-class="h-32 linh-32 br-16 px-12"
          @click="handleCancellOrder"
        />
        <TButton
          text="立即支付"
          type="none"
          :customStyle="{
            display: 'inline-block',
            backgroundColor: '#EA5E0E',
            color: '#FFFFFF',
            marginLeft: '20rpx',
          }"
          custom-class="h-32 linh-32 br-16 px-12"
          @click="handleToPay"
        />
      </TButtonGroup>
    </Loading>

    <!-- 关注公众号弹窗 -->
    <TencentCode
      :popupShow="tencentCodeShow"
      :followed-show="false"
      @close="handleTencentCodeClose"
    />
  </PageContainer>
</template>

<script lang="ts" setup>
  /* activityRegisterOrder 活动订单详情 */
  import { cancellOrder, getActivityOrderDetail } from '@/api/order';
  import Header from '@/components/Header/index.vue';
  import PageContainer from '@/components/PageContainer/index.vue';
  import TopActivityInfo from '../components/TopActivityInfo.vue';
  import CellBox, { type ListItem as CellBoxListItem } from '../components/CellBox.vue';
  import RegistrationInfo from './components/RegistrationInfo.vue';
  import TencentCode from '@/components/OfficialAccount/tencentCode.vue';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import TopStatusView from './components/TopStatusView.vue';
  import {
    type ActivityOrderDetailResult,
    type ActivityRegisterInfoItem,
    type ActivityShortDetailVo,
    type OrderDetails,
  } from '@/api/order/types';
  import { navigateTo, onLoad } from '@/router';
  import { ref } from 'vue';
  import { formatMoney } from '@/utils/number';
  import { Toast } from '@/utils';
  import { OrderPayStateEnum, OrderRefundStatusEnum, OrderStateEnum } from '@/enums/orderEnum';
  import Loading from '@/components/Loading/index.vue';
  import { requestPayment } from '../utils/payment';
  import type { ActivityRegisterOrder } from '@/router/types/modules';
  import { useUserStoreWithOut } from '@/store/modules/user';
  import { onPullDownRefresh } from '@dcloudio/uni-app';

  const useUser = useUserStoreWithOut();

  const tencentCodeShow = ref(false);
  function handleTencentCodeClose() {
    tencentCodeShow.value = false;
  }

  const loading = ref(true);
  const orderInfo = ref<OrderDetails>();
  const suborderInfo = ref<ActivityOrderDetailResult['suborder']>();
  const activityInfo = ref<ActivityShortDetailVo>();

  const applicantInfo = ref<CellBoxListItem[]>([]);
  const ticketPurchaseInfo = ref<CellBoxListItem[]>([]);
  const registerInfoList = ref<ActivityRegisterInfoItem[]>([]);

  let callback: ActivityRegisterOrder['callback'];

  onLoad<'activityRegisterOrder'>((op) => {
    callback = op.callback;
    if (op.scene === 'createActivityRegisterOrder' && !useUser.userInfo.isOfficialAccount) {
      tencentCodeShow.value = true;
    }
    __init(op.orderCode);
  });

  async function __init(orderCode?: string) {
    registerInfoList.value = [];
    if (!orderCode) orderCode = orderInfo.value?.orderCode as string;
    loading.value = true;
    const res = await getActivityOrderDetail(orderCode);
    orderInfo.value = res;
    const suborder = res.suborder;
    if (!suborder) return Toast('子订单信息为空');
    const { activityShortDetailVo, activityRegisterInfoList } = suborder;
    suborderInfo.value = suborder;
    activityInfo.value = activityShortDetailVo;
    registerInfoList.value = activityRegisterInfoList;

    applicantInfo.value = [
      { label: '报名提交人', value: suborder.submitName },
      { label: '提交时间', value: suborder.submitTime },
    ];

    let list: CellBoxListItem[] = [{ label: '报名类型', value: suborder?.activityTicketName }];
    if (suborder.totalDiscountMoney > 0) {
      list.push({
        label: `会员优惠`,
        value: `-${formatMoney({ money: suborder.totalDiscountMoney })}`,
      });
    }

    if (suborder.totalMoney > 0) {
      list = list.concat([
        { label: '费用总价', value: formatMoney({ money: suborder.totalMoney }) },
        {
          label: '实付金额',
          value: formatMoney({ money: suborder.payMoney }),
          valueColor: '#EA5E0E',
        },
      ]);
    }

    list = list.concat([
      { label: '订单编号', value: res.orderCode, showCuttingLine: true, showCopy: true },
      { label: '下单时间', value: res.createTime },
    ]);

    if (suborder.totalMoney > 0) {
      list.push({ label: '支付时间：', value: res.payTime });
    }
    ticketPurchaseInfo.value = list;
    loading.value = false;
    uni.stopPullDownRefresh();
  }

  /** 取消订单 */
  function handleCancellOrder() {
    uni.showModal({
      title: '取消订单',
      content: '确定要取消待付款订单吗？',
      confirmColor: '#EA5E0E',
      cancelColor: '#999996',
      confirmText: '立即取消',
      cancelText: '暂不取消',
      success: async (res) => {
        if (res.confirm) {
          await cancellOrder(orderInfo.value?.id as number);
          handleRefresh();
          Toast('取消成功');
        }
      },
    });
  }

  /** 支付 */
  function handleToPay() {
    if (orderInfo.value) {
      const { payCode } = orderInfo.value;
      requestPayment(payCode, false).then(() => {
        handleRefresh();
        !useUser.userInfo.isOfficialAccount && (tencentCodeShow.value = true);
      });
    }
  }

  function toActivityDetail() {
    navigateTo({
      name: 'activityDetails',
      options: {
        id: activityInfo.value?.activityId as number,
      },
    });
  }

  function handleRefresh() {
    callback?.();
    __init();
  }

  onPullDownRefresh(() => __init());
</script>

<style lang="scss" scoped>
  .label-color {
    color: #333;
  }
</style>
